import Cookie from 'js-cookie'
import Vue from 'vue'
import { emailLogin, tokenLogin, idLogin } from '@/api/login'
import { modifyData } from '@/api/myself'
export default {
  state: () => ({
    LoginStatus: false,
    user: {
    }
  }),
  mutations: {
    removeUser (state) {
      state.LoginStatus = false
      state.user = {}
      Cookie.remove('token')
    },
    setUser (state, user) {
      state.LoginStatus = true
      state.user = { ...user }
      Cookie.set('token', state.user.token, { expires: 3 })
    },
    modify (state, user) {
      state.user = { ...state.user, ...user }
    },
    star (state, id) {
      if (state.user.stars.findIndex(item => item === id) !== -1) {
        state.user.stars = state.user.stars.filter(item => item !== id)
      } else {
        state.user.stars.push(id)
      }
    },
    like (state, id) {
      if (state.user.likes.findIndex(item => item === id) !== -1) {
        state.user.likes = state.user.likes.filter(item => item !== id)
      } else {
        state.user.likes.push(id)
      }
    }
  },
  actions: {
    idLogin ({ commit }, userInfo) {
      const { uid, password } = userInfo
      return new Promise((resolve, reject) => {
        idLogin(uid, password).then(res => {
          commit('setUser', res.data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    tokenLogin ({ commit }) {
      const token = Cookie.get('token')
      if (token) {
        return new Promise((resolve, reject) => {
          tokenLogin(token).then(res => {
            commit('setUser', res.data)
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      }
    },
    emailLogin ({ commit }, userInfo) {
      const { verify, email } = userInfo
      return new Promise((resolve, reject) => {
        if (!verify || !email) {
          reject(Vue.prototype.$toast.fail('请输入完整信息'))
        }
        emailLogin(verify, email).then(res => {
          commit('setUser', res.data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    modifyData ({ commit }, userInfo) {
      const { email, icon, nickname, _id } = userInfo
      return new Promise((resolve, reject) => {
        modifyData(_id, icon, nickname, email).then(res => {
          console.log(res)
          commit('modify', res.data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}
